<template>
  <div class="content-management">
    <div class="page-header">
      <h2>内容管理</h2>
      <p>管理首页轮播图内容</p>
    </div>

    <el-card class="main-card" shadow="never" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>首页轮播图配置</span>
          <el-button type="primary" @click="handleAddCarousel">
            <el-icon><Plus /></el-icon>
            新增轮播图
          </el-button>
        </div>
      </template>

      <!-- 轮播图列表 -->
      <div class="carousel-list">
        <div
          v-for="(item, index) in carouselList"
          :key="index"
          class="carousel-item"
        >
          <div class="carousel-preview">
            <el-image
              :src="item.imageUrl"
              fit="cover"
              style="width: 200px; height: 100px"
              :preview-src-list="[item.imageUrl]"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                  <span>图片加载失败</span>
                </div>
              </template>
            </el-image>
          </div>

          <div class="carousel-info">
            <el-form-item label="轮播图图片">
              <el-upload
                :file-list="item.fileList || []"
                :action="API_CONFIG.UPLOAD_IMAGE_URL"
                list-type="picture-card"
                :headers="uploadHeaders"
                :on-success="(response, file) => handleImageUploadSuccess(response, file, index)"
                :on-error="handleImageUploadError"
                :on-remove="(file) => handleImageRemove(file, index)"
                :before-upload="beforeImageUpload"
                :limit="1"
                accept="image/*"
              >
                <el-icon><Plus /></el-icon>
                <template #tip>
                  <div class="el-upload__tip">
                    支持 jpg/png/gif 格式，单张图片不超过 2MB
                  </div>
                </template>
              </el-upload>
            </el-form-item>
            <el-form-item label="图片URL">
              <el-input
                v-model="item.imageUrl"
                placeholder="上传图片后自动填充，也可手动输入"
                style="width: 400px"
              />
            </el-form-item>
            <el-form-item label="跳转链接">
              <el-input
                v-model="item.link"
                placeholder="请输入跳转链接（可选）"
                style="width: 400px"
              />
            </el-form-item>
          </div>

          <div class="carousel-actions">
            <el-button
              :disabled="index === 0"
              @click="moveUp(index)"
              size="small"
            >
              <el-icon><ArrowUp /></el-icon>
              上移
            </el-button>
            <el-button
              :disabled="index === carouselList.length - 1"
              @click="moveDown(index)"
              size="small"
            >
              <el-icon><ArrowDown /></el-icon>
              下移
            </el-button>
            <el-button
              type="danger"
              @click="removeCarousel(index)"
              size="small"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="carouselList.length === 0" class="empty-state">
          <el-empty description="暂无轮播图配置">
            <el-button type="primary" @click="handleAddCarousel">
              新增轮播图
            </el-button>
          </el-empty>
        </div>
      </div>

      <!-- 保存按钮 -->
      <div class="save-actions" v-if="carouselList.length > 0">
        <el-button type="primary" @click="handleSave" :loading="saveLoading">
          <el-icon><Check /></el-icon>
          保存配置
        </el-button>
        <el-button @click="handleReset">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Picture,
  ArrowUp,
  ArrowDown,
  Delete,
  Check,
  Refresh
} from '@element-plus/icons-vue'
import { getSystemConfig, updateSystemConfig } from '@/api/systemConfig'
import { useUserStore } from '@/stores/user'
import { API_CONFIG } from '@/config'

// 轮播图数据类型
interface CarouselItem {
  imageUrl: string
  link: string
  fileList?: any[]
}

// 响应式数据
const loading = ref(false)
const saveLoading = ref(false)
const carouselList = ref<CarouselItem[]>([])
const originalData = ref<CarouselItem[]>([])

// 用户store
const userStore = useUserStore()

// 上传请求头
const uploadHeaders = computed(() => ({
  'Authorization': `Bearer ${userStore.token}`
}))

/**
 * 获取轮播图配置
 */
const fetchCarouselConfig = async () => {
  try {
    loading.value = true
    const response = await getSystemConfig('homepage_carousel')

    if (response.success) {
      const configValue = response.data.config_value
      try {
        const parsedData = JSON.parse(configValue)
        if (Array.isArray(parsedData)) {
          carouselList.value = parsedData.map((item, index) => ({
            ...item,
            fileList: item.imageUrl ? [{
              uid: `carousel_${Date.now()}_${index}`,
              name: `carousel_${index + 1}.jpg`,
              status: 'done',
              url: item.imageUrl.startsWith('/uploads/') ? `${API_CONFIG.SERVER_URL}${item.imageUrl}` : item.imageUrl,
              originalUrl: item.imageUrl
            }] : []
          }))
        } else {
          carouselList.value = []
        }
        originalData.value = JSON.parse(JSON.stringify(carouselList.value))
      } catch (parseError) {
        console.warn('解析轮播图配置失败:', parseError)
        carouselList.value = []
        originalData.value = []
      }
    } else {
      // 配置不存在时初始化为空数组
      carouselList.value = []
      originalData.value = []
    }
  } catch (error) {
    // 如果是404错误（配置不存在），这是正常情况
    if (error.response && error.response.status === 404) {
      console.log('轮播图配置不存在，初始化为空配置')
      carouselList.value = []
      originalData.value = []
    } else {
      console.error('获取轮播图配置错误:', error)
      carouselList.value = []
      originalData.value = []
    }
  } finally {
    loading.value = false
  }
}

/**
 * 新增轮播图
 */
const handleAddCarousel = () => {
  carouselList.value.push({
    imageUrl: '',
    link: '',
    fileList: []
  })
}

/**
 * 上移轮播图
 */
const moveUp = (index: number) => {
  if (index > 0) {
    const temp = carouselList.value[index]
    carouselList.value[index] = carouselList.value[index - 1]
    carouselList.value[index - 1] = temp
  }
}

/**
 * 下移轮播图
 */
const moveDown = (index: number) => {
  if (index < carouselList.value.length - 1) {
    const temp = carouselList.value[index]
    carouselList.value[index] = carouselList.value[index + 1]
    carouselList.value[index + 1] = temp
  }
}

/**
 * 删除轮播图
 */
const removeCarousel = async (index: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个轮播图吗？',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    carouselList.value.splice(index, 1)
  } catch (error) {
    // 用户取消删除
  }
}

/**
 * 图片上传前验证
 */
const beforeImageUpload = (file: any) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

/**
 * 图片上传成功回调
 */
const handleImageUploadSuccess = (response: any, file: any, index: number) => {
  if (response.success && response.data?.url) {
    // 更新轮播图的图片URL
    carouselList.value[index].imageUrl = response.data.url

    // 更新文件列表
    const fileIndex = carouselList.value[index].fileList?.findIndex(item => item.uid === file.uid)
    if (fileIndex !== -1 && carouselList.value[index].fileList) {
      carouselList.value[index].fileList[fileIndex].url = `${API_CONFIG.SERVER_URL}${response.data.url}`
      carouselList.value[index].fileList[fileIndex].status = 'done'
      carouselList.value[index].fileList[fileIndex].originalUrl = response.data.url
    }

    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(response.message || '图片上传失败')
  }
}

/**
 * 图片上传失败回调
 */
const handleImageUploadError = (error: any) => {
  console.error('图片上传失败:', error)
  ElMessage.error('图片上传失败，请重试')
}

/**
 * 图片删除回调
 */
const handleImageRemove = (file: any, index: number) => {
  // 清空图片URL
  carouselList.value[index].imageUrl = ''
  // 清空文件列表
  carouselList.value[index].fileList = []
}

/**
 * 保存配置
 */
const handleSave = async () => {
  try {
    // 验证数据
    const invalidItems = carouselList.value.filter(item => !item.imageUrl.trim())
    if (invalidItems.length > 0) {
      ElMessage.error('请为所有轮播图上传图片或填写图片URL')
      return
    }

    saveLoading.value = true

    // 准备保存的数据，去除fileList字段
    const saveData = carouselList.value.map(item => ({
      imageUrl: item.imageUrl,
      link: item.link
    }))

    const configData = {
      config_key: 'homepage_carousel',
      config_value: JSON.stringify(saveData),
      description: '首页轮播图配置'
    }

    const response = await updateSystemConfig(configData)

    if (response.success) {
      ElMessage.success('保存成功')
      originalData.value = JSON.parse(JSON.stringify(carouselList.value))
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error) {
    console.error('保存轮播图配置错误:', error)
    ElMessage.error('保存失败')
  } finally {
    saveLoading.value = false
  }
}

/**
 * 重置配置
 */
const handleReset = () => {
  carouselList.value = JSON.parse(JSON.stringify(originalData.value))
  ElMessage.info('已重置为上次保存的配置')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCarouselConfig()
})
</script>

<style scoped>
.content-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.main-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.carousel-list {
  min-height: 200px;
}

.carousel-item {
  display: flex;
  align-items: flex-start;
  gap: 20px;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  margin-bottom: 16px;
  background-color: #fafafa;
}

.carousel-preview {
  flex-shrink: 0;
}

.carousel-info {
  flex: 1;
}

.carousel-info .el-form-item {
  margin-bottom: 16px;
}

.carousel-actions {
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.image-slot {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #c0c4cc;
  font-size: 12px;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.save-actions {
  text-align: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.save-actions .el-button {
  margin: 0 8px;
}

/* 上传组件样式调整 */
:deep(.el-upload--picture-card) {
  width: 100px;
  height: 60px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 100px;
  height: 60px;
}

:deep(.el-upload-list__item-thumbnail) {
  object-fit: cover;
}
</style>
